# -*- coding: utf-8 -*-
#
# Copyright 2009 Vanderbilt University
# 
# Licensed under the Apache License, Version 2.0 (the "License"); 
# you may not use this file except in compliance with the License. 
# You may obtain a copy of the License at 
# 
#     http://www.apache.org/licenses/LICENSE-2.0 
# 
# Unless required by applicable law or agreed to in writing, software 
# distributed under the License is distributed on an "AS IS" BASIS, 
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
# See the License for the specific language governing permissions and 
# limitations under the License. 

"""Allows graphs to be serialized/deserialized to disk, prevent unnecessary
computations every time analyses need to be run on an unchanging network.

.. moduleauthor:: John Paulett <john.paulett -at- vanderbilt.edu>
"""
from hornet.event import GraphsReady, ProcessingStart
from hornet.file import serialize, deserialize, join, list_dir
from hornet.plugin import Plugin, log, notify_on_finish
import logging

logger = logging.getLogger(__name__)
FILE_EXTENSION = '.graph'

# TODO: compress files in bz2
# import bz2, pickle
# gs = pickle.dumps(graph)
# gc = bz2.compress(gs)
# f = file('output.graph.bz2', 'wb')
# f.write(gc)
# f.close()
def get_file_name(data_dir, graph):
    fn = '%s%s' % (graph.name, FILE_EXTENSION)
    return join(data_dir, fn)

def save_graphs(data_dir, graphs):
    for graph in graphs:
        fn = get_file_name(data_dir, graph)
        logger.info('Saving %s' % fn)
        serialize(fn, graph)
        logger.info('Finished saving %s' % fn)

def open_graphs(data_dir):
    # TODO: make this more selective so as to not grab everything in the folder
    files = [path for path in list_dir(data_dir) if path.endswith(FILE_EXTENSION)]
    return [deserialize(join(data_dir, f)) for f in files]

class GraphOpener(Plugin):
    def __init__(self, data_dir):
        self.data_dir = data_dir
    
    def accepted_events(self):
        return ProcessingStart
    
    @notify_on_finish
    @log
    def notify(self, event):
        graphs = open_graphs(self.data_dir)
        return GraphsReady(graphs)

class GraphSaver(Plugin):
    def __init__(self, data_dir):
        self.data_dir = data_dir

    def accepted_events(self):
        return GraphsReady
    
    @log
    def notify(self, event):
        save_graphs(self.data_dir, event.data)
        